from numbers import Number

import requests
import os
import sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from sendEmil import send_email
from datetime import datetime
import webbrowser
import re
token = 'eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJVU0VSX0xPR0lOX1JFRElTX0tFWV9QQzpML2hSUUtYVVp2SVNPZ2duL0p3enhRPT06MTE0LjI1NS4yMzAuMzAiLCJpYXQiOjE3NjM0NTIwNTcsImV4cCI6MTc2NDA1Njg1N30.J-CcS_3qnT0CBwdRzP4J5uV1fvGv-ZmhiCVDcsNyb_HRDD6HCw1S_Lf61TPfYUcDwgPQD5ocLMpj7J-i-U25fQ'





# Note: json_data will not be serialized by requests
# exactly as it was in the original request.
# data = '{"authorId":null,"chainContract":null,"commodityCategoryId":null,"commodityCategoryIdList":[],"commodityId":null,"highPrice":"","lowPrice":"","pageCount":1,"pageSize":20,"seriesWorks":null,"seriesWorksId":null,"sort":null,"topicId":null,"typeMarket":2,"tnsTraitUuidList":[],"statusSell":"","commodityTraitList":[]}'
# response = requests.post('https://api.theone.art/market/api/saleRecord/commodity/List', headers=headers, data=data)






def buy(id,price):
	json_data = [
		{
			'saleRecordAmount': 1,
			'saleRecordId': id,
			'amountPay': price,
		},
	]
	headers = {
		'Accept': 'application/json, text/plain, */*',
		'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
		'Cache-Control': 'no-cache',
		'Connection': 'keep-alive',
		'Content-Type': 'application/json;charset=UTF-8',
		'Origin': 'https://www.theone.art',
		'Pragma': 'no-cache',
		'Referer': 'https://www.theone.art/buy/81c947cf76adb2e5d889dcacdba393b1',
		'Sec-Fetch-Dest': 'empty',
		'Sec-Fetch-Mode': 'cors',
		'Sec-Fetch-Site': 'same-site',
		'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36',
		'authorization': token,
		'sec-ch-ua': '"Not(A:Brand";v="99", "Google Chrome";v="133", "Chromium";v="133"',
		'sec-ch-ua-mobile': '?0',
		'sec-ch-ua-platform': '"Windows"',
	}



	response = requests.post('https://api.theone.art/order/api/orderBuy/add', headers=headers, json=json_data).json()

	# Note: json_data will not be serialized by requests
	# exactly as it was in the original request.
	# data = '[{"saleRecordAmount":1,"saleRecordId":"81c947cf76adb2e5d889dcacdba393b1","amountPay":"75000"}]'
	# response = requests.post('https://api.theone.art/order/api/orderBuy/add', headers=headers, data=data)
	return response

while True:
	productids = []


	# 获取productids
	def getprodutids(i):
		headers = {
			'Accept': 'application/json, text/plain, */*',
			'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
			'Cache-Control': 'no-cache',
			'Connection': 'keep-alive',
			'Content-Type': 'application/json;charset=UTF-8',
			'Origin': 'https://www.theone.art',
			'Pragma': 'no-cache',
			'Referer': 'https://www.theone.art/market?type=derive&category_id=7928dcb378475f97688da730ef0e0658&curPage=derive',
			'Sec-Fetch-Dest': 'empty',
			'Sec-Fetch-Mode': 'cors',
			'Sec-Fetch-Site': 'same-site',
			'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36',
			'authorization': 'eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJVU0VSX0xPR0lOX1JFRElTX0tFWV9QQzpML2hSUUtYVVp2SVNPZ2duL0p3enhRPT06MTE0LjI1NS4yMzAuMzAiLCJpYXQiOjE3NjM0NTIwNTcsImV4cCI6MTc2NDA1Njg1N30.J-CcS_3qnT0CBwdRzP4J5uV1fvGv-ZmhiCVDcsNyb_HRDD6HCw1S_Lf61TPfYUcDwgPQD5ocLMpj7J-i-U25fQ',
			'sec-ch-ua': '"Chromium";v="142", "Google Chrome";v="142", "Not_A Brand";v="99"',
			'sec-ch-ua-mobile': '?0',
			'sec-ch-ua-platform': '"Windows"',
		}

		json_data = {
			'authorId': None,
			'chainContract': None,
			'commodityCategoryId': None,
			'commodityCategoryIdList': [],
			'commodityId': None,
			'highPrice': '',
			'lowPrice': '',
			'pageCount': i,
			'pageSize': 20,
			'seriesWorks': None,
			'seriesWorksId': None,
			'sort': None,
			'topicId': None,
			'typeMarket': 2,
			'tnsTraitUuidList': [],
			'statusSell': '',
			'commodityTraitList': [],
		}

		response = requests.post('https://api.theone.art/market/api/saleRecord/commodity/List', headers=headers,
								 json=json_data)
		data = response.json()

		# print(data['data'].records)
		res = data['data']['records']
		for item in res:
			if(item['statusSale'] != 2):
				productids.append(
					{'name': item['commodity']['name'], 'id': item['commodity']['id'],
					 'price': int(float(item['price'])), 'statusSale': item['statusSale']})



	for i in range(1, 6):
		getprodutids(i)

	print(productids)
	# 获取当前时间
	now = datetime.now()
	# 格式化时间为时分秒
	current_time = now.strftime("%H:%M:%S")
	# 打印时分秒
	print("----------------------------------------当前时间:", current_time)
	# 遍历所有商品ID
	for product_id in productids:
		headers = {
			'Accept': 'application/json, text/plain, */*',
			'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
			'Cache-Control': 'no-cache',
			'Connection': 'keep-alive',
			'Content-Type': 'application/json;charset=UTF-8',
			'Origin': 'https://www.theone.art',
			'Pragma': 'no-cache',
			'Referer': 'https://www.theone.art/derivative/8a6684374652c3dcf293eb03d51b990f/1',
			'Sec-Fetch-Dest': 'empty',
			'Sec-Fetch-Mode': 'cors',
			'Sec-Fetch-Site': 'same-site',
			'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36',
			'authorization': token,
			'sec-ch-ua': '"Not(A:Brand";v="99", "Google Chrome";v="133", "Chromium";v="133"',
			'sec-ch-ua-mobile': '?0',
			'sec-ch-ua-platform': '"Windows"',
		}

		json_data = {
			'commodityId': product_id['id'],
			'pageCount': 1,
			'pageSize': 20,
			'saleLock':2,
			'sort': {
				'field': 2,
				'upOrDown': 2,
			},
			'typeMarket':2
		}
		try:
			response = requests.post('https://api.theone.art/market/api/wantBuy/list/v2', headers=headers, json=json_data).json()
			list = response['data']

			# 把list列表 paytype为2的全部去掉
			list = [item for item in list if item['payType'] == 2]
			if(len(list) < 1):
				continue
			match = re.search(r'\d+\.\d+', list[0]['price'])
			pleaseHprice = int(float(match.group()))
			# print('当前请求的最高价格', pleaseHprice)
			# 判断价格差异改为50%
			print(product_id['name'],'当前请求id的最低价格：：：',product_id['price'],'当前id求购最高的价格:::',pleaseHprice)
			if(product_id['statusSale']==2):
				continue
			if(product_id['price'] < pleaseHprice):

				json_data2 = {
					'commodityId': product_id['id'],
					'pageCount': 1,
					'pageSize': 20,
					'sort': {
						'field': 2,
						'upOrDown': 1,
					},
				}
				response2 = requests.post('https://api.theone.art/market/api/saleRecord/list/v3', headers=headers,
										 json=json_data2).json()
				list2 = response['data']['records']
				if(len(list2) >= 1):
					print('发现低价商品!')
					res = buy(list2[0]['id'], int(float(list[0]['price'])) * 100)
					print(res)
					if (res['code'] == 200):
						content = (f'商品: {list[0]["commodity"]["name"]}\n'
								   f'价格: {list[0]["price"]}\n'
								   f'商品列表 {list[1]["price"]}\n'
								   f'商品列表 {list[2]["price"]}\n'
								   f'商品列表 {list[3]["price"]}\n'
								   f'https://www.theone.art/mine/buy'
								   )
					send_email('唯一', content)
					print('https://www.theone.art/mine/buy')
					url = "https://www.douyin.com/user/self?from_tab_name=main&modal_id=7190605186274954536&showTab=like"
					webbrowser.open(url)
					exit()







			# if float(list[0]['price']) <= float(list[1]['price']) * 0.4:
			# 	print('发现低价商品!')


		except Exception as e:
			print(f'检查商品 {product_id["name"]} 时发生错误:')
			continue



